//
//  MAEnteringVC.m
//  meiang_edu
//
//  Created by Apple on 2018/10/22.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAEnteringVC.h"
#import "TZImagePickerController.h"
#import "Toast.h"
#import "AFNetworking.h"
@interface MAEnteringVC ()
<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIView* collectBgView;
    double latitude;
    double longitude;
    OSSClient * client;
    
    UIView *popCancleDiaglogView;
    UIView *popCancleDiaglogBgView;
}
@property(nonatomic,strong) UIImageView *leftIcon;
@property(nonatomic,strong) UIImageView *rightIcon;
@property(nonatomic,strong) UITextView *inputContent;
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong)UILabel* placeholderLabel;
@property(nonatomic,strong)NSMutableArray *imageArr;
@property(nonatomic,strong)UIView *locationView;
@property(nonatomic,strong)UILabel *locationLabel;
@property(nonatomic,strong)AFHTTPSessionManager *saveManager;

@end

@implementation MAEnteringVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"通用录入";
    self.view.backgroundColor=[UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1.00];
    
    [self.leftIcon addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBtnDidClick)]];
    [self.leftIcon setImage:[UIImage imageNamed:@"back"]];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 7.0, 15, 25.0)];
    [leftView addSubview:self.leftIcon];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    self.view.backgroundColor=[UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1.00];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 0.0, 35.0, 35.0)];
    [rightBtn addTarget:self action:@selector(rightBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"savebutton_logo"] forState:UIControlStateNormal];
    //编辑
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 35.0, 35.0)];
    [view addSubview:rightBtn];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self initWithView];
    [self initLocation];
    [self popDialogView];
}

- (UIImageView *)leftIcon {
    if (_leftIcon == nil) {
        UIImageView *leftBtn = [[UIImageView alloc] init];
        leftBtn.width = 15;
        leftBtn.height = 25.0;
        leftBtn.x = -3;
        leftBtn.y = 0;
        leftBtn.userInteractionEnabled = YES;
        _leftIcon = leftBtn;
    }
    return _leftIcon;
}


-(void)initWithView{
    //内容
    _inputContent=[[UITextView alloc] initWithFrame:CGRectMake(6,74, kScreenWidth-12,50)];
    _inputContent.text=@"";
    _inputContent.textColor=[UIColor colorWithRed:0.600 green:0.600 blue:0.600 alpha:1.00];
    _inputContent.font=[UIFont systemFontOfSize:15];
    _inputContent.delegate=self;
    _inputContent.backgroundColor=[UIColor whiteColor];
    _inputContent.returnKeyType=UIReturnKeyDone;
    _inputContent.layer.masksToBounds=YES;
    _inputContent.layer.cornerRadius=10;
    _inputContent.contentInset = UIEdgeInsetsMake(7,0, 0, 0);//调整光标的位置
    [self.view addSubview:_inputContent];
    
    _placeholderLabel=[[UILabel alloc] initWithFrame:CGRectMake(22,74,kScreenWidth-40,50)];
    _placeholderLabel.textColor=[UIColor lightGrayColor];
    _placeholderLabel.text=@"请在此输入内容";
    _placeholderLabel.backgroundColor=[UIColor clearColor];
    _placeholderLabel.enabled=NO;
    _placeholderLabel.font=[UIFont systemFontOfSize:15];
    [self.view addSubview:_placeholderLabel];
    
    //图片
    collectBgView=[[UIView alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12, 230)];
    collectBgView.backgroundColor=[UIColor whiteColor];
    collectBgView.layer.masksToBounds=YES;
    collectBgView.layer.cornerRadius=10;
    [self.view addSubview:collectBgView];
    //布局
    UICollectionViewFlowLayout* layout=[[UICollectionViewFlowLayout alloc] init];
    if (kScreenHeight<736&&kScreenHeight>568) {
        layout.itemSize = CGSizeMake(60, 60);//每个cell的大小
        layout.minimumInteritemSpacing=5;                                     //每行的最小间距
        layout.minimumLineSpacing = 5;
        collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12, 80);
        
        //每列的最小间距
    }else if(kScreenHeight<=568){
        layout.itemSize = CGSizeMake(55, 55);//每个cell的大小
        layout.minimumInteritemSpacing=5;                                     //每行的最小间距
        layout.minimumLineSpacing = 5;
        collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12, 75);
        
        //每列的最小间距
    }else{
        layout.itemSize = CGSizeMake(70, 70);//每个cell的大小
        layout.minimumInteritemSpacing=10;                                     //每行的最小间距
        layout.minimumLineSpacing = 10;
         collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12, 90);
        //每列的最小间距
    }
    
    _imageArr=[[NSMutableArray alloc] initWithCapacity:0];
    //网格视图
    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(6, 6, collectBgView.frame.size.width-12,210) collectionViewLayout:layout];
    _collectionView.backgroundColor=[UIColor whiteColor];
    UINib *cellNib = [UINib nibWithNibName:@"WriteDynamicImageCell" bundle:nil];
    [_collectionView registerNib:cellNib forCellWithReuseIdentifier:@"WriteDynamicImageCell"];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.showsHorizontalScrollIndicator=NO;
    _collectionView.showsVerticalScrollIndicator=NO;
    _collectionView.alwaysBounceVertical = NO;
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [collectBgView addSubview:_collectionView];
    
    _locationView=[[UIView alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(collectBgView.frame)+10, kScreenWidth-12,50)];
    _locationView.backgroundColor=[UIColor whiteColor];
    _locationView.layer.masksToBounds=YES;
    _locationView.layer.cornerRadius=10;
    [self.view addSubview:_locationView];
    
    UILabel * label1=[[UILabel alloc] initWithFrame:CGRectMake(6, 0, 80, 50)];
    label1.text=@"定位";
    label1.textColor=[UIColor colorWithRed:0.600 green:0.600 blue:0.600 alpha:1.00];
    label1.font=[UIFont systemFontOfSize:15];
    [_locationView addSubview:label1];
    
    _locationLabel=[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label1.frame)+10, 0, _locationView.frame.size.width-(CGRectGetMaxX(label1.frame)+20), 50)];
    _locationLabel.text=@"定位请点击";
    _locationLabel.textAlignment=NSTextAlignmentRight;
    _locationLabel.font=[UIFont systemFontOfSize:15];
    _locationLabel.textColor=[UIColor colorWithRed:0.600 green:0.600 blue:0.600 alpha:1.00];
    _locationLabel.userInteractionEnabled=YES;
    [_locationView addSubview:_locationLabel];
    UITapGestureRecognizer *locationTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(locationTap:)];
    [_locationLabel addGestureRecognizer:locationTap];
}

#pragma mark 定位
-(void)initLocation{
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
}


-(void)popDialogView{
    popCancleDiaglogBgView=[[UIView alloc] initWithFrame:self.view.frame];
    popCancleDiaglogBgView.hidden=YES;
    popCancleDiaglogBgView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.view addSubview:popCancleDiaglogBgView];
    popCancleDiaglogView=[[UIView alloc] initWithFrame:CGRectMake((kScreenWidth-250)/2.0,(kScreenHeight-150)/2.0, 250, 150)];
    popCancleDiaglogView.backgroundColor=[UIColor whiteColor];
    popCancleDiaglogView.layer.masksToBounds=YES;
    popCancleDiaglogView.layer.cornerRadius=10;
    [popCancleDiaglogBgView addSubview:popCancleDiaglogView];
    
    UILabel *titlelabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0,250 ,40)];
    titlelabel.backgroundColor=[UIColor colorWithRed:0.000 green:0.690 blue:0.831 alpha:1.00];
    titlelabel.text=@"温馨提示";
    titlelabel.textColor=[UIColor whiteColor];
    titlelabel.font=[UIFont systemFontOfSize:15];
    titlelabel.textAlignment=NSTextAlignmentCenter;
    [popCancleDiaglogView addSubview:titlelabel];
    
    UILabel *contentLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titlelabel.frame)+20, 250, 20)];
    contentLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    contentLabel.text=@"您是否放弃本次编辑";
    contentLabel.font=[UIFont systemFontOfSize:15];
    contentLabel.textAlignment=NSTextAlignmentCenter;
    [popCancleDiaglogView addSubview:contentLabel];
    
    UIButton *cancleBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame=CGRectMake(0, 110, 125,40);
    cancleBtn.backgroundColor=[UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1.00];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00] forState:UIControlStateNormal];
    [cancleBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [cancleBtn addTarget:self action:@selector(cancle:) forControlEvents:UIControlEventTouchUpInside];
    [popCancleDiaglogView addSubview:cancleBtn];
    
    UIButton *sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame=CGRectMake(125, 110, 125,40);
    sureBtn.backgroundColor=[UIColor colorWithRed:0.000 green:0.690 blue:0.831 alpha:1.00];
    [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [sureBtn addTarget:self action:@selector(sure:) forControlEvents:UIControlEventTouchUpInside];
    [popCancleDiaglogView addSubview:sureBtn];
}

-(void)cancle:(UIButton *)b{
    popCancleDiaglogBgView.hidden=YES;
}

-(void)sure:(UIButton *)b{
    [self.navigationController popViewControllerAnimated:YES];
    popCancleDiaglogBgView.hidden=YES;
}

#pragma mark 返回
-(void)leftBtnDidClick{
    popCancleDiaglogBgView.hidden=NO;
}

#pragma mark 提交编辑
-(void)rightBtnDidClick{
    [self loadOSSKey];
    
}

#pragma mark 获取阿里云的信息
-(void)loadOSSKey{
    if ([_inputContent.text isEqualToString:@""]) {
        [Toast showWithText:@"请输入内容" duration:1];
        return;
    }
    if (_imageArr.count==0) {
        [Toast showWithText:@"请选择照片" duration:1];
        return;
    }
    if ([_locationLabel.text isEqualToString:@"定位请点击"]) {
        [Toast showWithText:@"请点击定位获取您的地理位置" duration:1];
        return;
    }
    [MBManager showLoading];
    NSMutableArray *image_guid=[[NSMutableArray alloc] init];
    for (int i=0; i<_imageArr.count; i++) {
        NSString  *uuid=[[MAToolUtils stringWithUUID] lowercaseString];
        [image_guid addObject:uuid];
    }
    
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@",GetStsToken_URL];
        request.methodType = ZBMethodTypePOST;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"获取oss===%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            NSString *accesskeysecret=[[dataDict objectForKey:@"value"] objectForKey:@"accesskeysecret"];
            NSString *accesskeyid=[[dataDict objectForKey:@"value"] objectForKey:@"accesskeyid"];
            NSString *securitytoken=[[dataDict objectForKey:@"value"] objectForKey:@"securitytoken"];
            NSString *expiration=[[dataDict objectForKey:@"value"] objectForKey:@"expiration"];
            //初始化ALiOSS
            [self initAli:accesskeysecret :accesskeyid:securitytoken:expiration :image_guid];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
    
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
            
        }
    }];
}

#pragma mark 上传图片
-(void)initAli:(NSString *)accesskeysecret :(NSString *)accesskeyid :(NSString *)securitytoken :(NSString *)expiration :(NSMutableArray *)image_guid {
    OSSFederationToken * token = [OSSFederationToken new];
    token.tAccessKey = accesskeyid;
    token.tSecretKey = accesskeysecret;
    token.tToken = securitytoken;
    token.expirationTimeInGMTFormat = expiration;
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc]initWithFederationTokenGetter:^OSSFederationToken *{
        return token;
    }];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =30;
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 *60 * 60;
    // 你的阿里地址前面通常是这种格式 :http://oss……
    client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-beijing.aliyuncs.com" credentialProvider:credential];
    for (int i=0; i<_imageArr.count; i++) {
        UIImage *image=[_imageArr objectAtIndex:i];
        NSData  *imageData=UIImagePNGRepresentation(image);
        [self updateToALi:imageData imageName:[image_guid objectAtIndex:i] imageGuid:image_guid];
    }
}

#pragma mark 上传图片
- (void)updateToALi:(NSData *)data imageName:(NSString *)imageName imageGuid:(NSMutableArray *)image_guid{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName =@"armyant";
    put.objectKey = imageName;
    put.uploadingData = data; // 直接上传NSData
    
    __weak MAEnteringVC  *weakself=self;
    
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent,int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        if (totalByteSent==totalBytesExpectedToSend) {
            [weakself infoamtionSave:image_guid];
        }
    };
    OSSTask * putTask = [client putObject:put];
    // 上传阿里云
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!==%d",index);
           
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
}

#pragma mark 信息保存
-(void)infoamtionSave:(NSMutableArray *)image_guid{
    
     MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString =[NSString stringWithFormat:@"%@%@",SavePutInfo_url,userinfo.cuserid];
        request.methodType = ZBMethodTypePOST;
        [request setValue:userinfo.token forHeaderField:@"token"];
        [request setValue:@"application/text;charset=utf-8" forHeaderField:@"Content-Type"];
        request.apiType = ZBRequestTypeRefresh;
        NSMutableDictionary *parmars=[[NSMutableDictionary  alloc] init];
        [parmars setObject:userinfo.ID forKey:@"us_idinput"];
        [parmars setObject:[NSString stringWithFormat:@"%ld",_imageArr.count] forKey:@"image_count"];
        NSString *image_guid_str=[image_guid componentsJoinedByString:@","];
        [parmars setObject:image_guid_str forKey:@"image_list"];
        [parmars setObject:[NSString stringWithFormat:@"%@,%@",[NSNumber numberWithDouble:latitude],[NSNumber numberWithDouble:longitude]] forKey:@"clocation"];
        [parmars setObject:_locationLabel.text forKey:@"clocationname"];
        [parmars setObject:_inputContent.text forKey:@"cnotes"];
        [parmars setObject:@"" forKey:@"ch_id"];//学生ID
        [parmars setObject:@"" forKey:@"ph_id"];
        [parmars setObject:@"" forKey:@"iscope"];
        [parmars setObject:_sender_key forKey:@"or_id"];
        [parmars setObject:@"" forKey:@"ccaption"];
        [parmars setObject:_message_typechild forKey:@"giscene"];
        [parmars setObject:_messageID forKey:@"parent_cid"];
        [request setParameters:[parmars mj_JSONObject]];

    } success:^(id responseObject, apiType type) {
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"保存信息===%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
           [MBManager hideAlert];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);

    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

#pragma mark 定位转中文
-(void)locationTap:(UITapGestureRecognizer *)tap{
    [MBManager showLoading];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@&pois=1",LOCATION_INFO,[NSString stringWithFormat:@"%@,%@",[NSNumber numberWithDouble:latitude],[NSNumber numberWithDouble:longitude]]];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"地理位置%@",dataDict);
        NSDictionary *result=[dataDict objectForKey:@"result"];
        self.locationLabel.text=[result objectForKey:@"formatted_address"];
    } failure:^(NSError *error) {

        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            NSLog(@"使用了缓存");
        }
    }];
}



#pragma mark 百度地图定位

//处理方向变更信息
-(void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    //    NSLog(@"heading is %@",userLocation.heading);
}

//处理位置坐标更新
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    latitude=userLocation.location.coordinate.latitude;
    longitude=userLocation.location.coordinate.longitude;
    NSLog(@"latitude==%@,longitude===%@",[NSNumber numberWithDouble:latitude],[NSNumber numberWithDouble:longitude]);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark *placemark = [placemarks firstObject];
            NSString* city=placemark.locality;
            NSLog(@"city===%@",city);
        }
    }];

    _locService.delegate = nil;
    [_locService stopUserLocationService];
}



#pragma  mark - 网格视图代理

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageArr.count+1;
    
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==_imageArr.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WriteDynamicImageCell" forIndexPath:indexPath];
        UIImageView* imageView=(UIImageView*)[cell viewWithTag:100];
        [imageView setImage:[UIImage imageNamed:@"addimage_logo"]];
        imageView.contentMode=UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds=YES;
        UIButton* deleBtn=[cell viewWithTag:101];
        deleBtn.hidden=YES;
        return cell;
    }
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WriteDynamicImageCell" forIndexPath:indexPath];
    cell.contentView.tag=indexPath.row;
    UIImageView* imageView=(UIImageView*)[cell viewWithTag:100];
    [imageView setImage:[_imageArr objectAtIndex:indexPath.row]];
    UIButton* deleBtn=[cell viewWithTag:101];
    deleBtn.hidden=NO;
    [deleBtn addTarget:self action:@selector(deleImage:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==_imageArr.count) {
        [_inputContent resignFirstResponder];
        UIActionSheet* actionSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
        [actionSheet showInView:self.view];
    }else{
        UICollectionViewCell *cell=[collectionView cellForItemAtIndexPath:indexPath];
        UIImageView* imageView=(UIImageView*)[cell viewWithTag:100];
//        [HUPhotoBrowser showFromImageView:imageView withImages:_imageArr atIndex:indexPath.row andTag:2].delegate=self;
    }
}

#pragma mark 删除
-(void)deleImage:(UIButton *)b{
    UICollectionViewCell *cell=(UICollectionViewCell*)b.superview;
    NSLog(@"cell.tag===========%ld",(long)cell.tag);
    [_imageArr removeObjectAtIndex:cell.tag];
    if (_imageArr.count<5) {
        collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12,80);
        _collectionView.frame=CGRectMake(6, 6,collectBgView.frame.size.width-12,collectBgView.frame.size.height-12);
        _locationView.frame=CGRectMake(6, CGRectGetMaxY(collectBgView.frame)+10, kScreenWidth-12,50);
    }
    [_collectionView reloadData];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        //相机
        if (_imageArr.count>8) {
            [Toast showWithText:@"最多上传9张" duration:1];
            return;
        }
        [self  pickImageFromCamera];
    }else if (buttonIndex==1){
        //相册
        if (_imageArr.count>8) {
            [Toast showWithText:@"最多上传9张" duration:1];
            return;
        }
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        
        // You can get the photos by block, the same as by delegate.
        // 你可以通过block或者代理，来得到用户选择的照片.
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            [_imageArr addObjectsFromArray:photos];
            if (_imageArr.count>=5) {
                collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12,160);
                _collectionView.frame=CGRectMake(6, 6,collectBgView.frame.size.width-12,collectBgView.frame.size.height-12);
                _locationView.frame=CGRectMake(6, CGRectGetMaxY(collectBgView.frame)+10, kScreenWidth-12,50);
                [_collectionView reloadData];
            }else{
                collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12,80);
                _collectionView.frame=CGRectMake(6, 6,collectBgView.frame.size.width-12,collectBgView.frame.size.height-12);
                _locationView.frame=CGRectMake(6, CGRectGetMaxY(collectBgView.frame)+10, kScreenWidth-12,50);
                [_collectionView reloadData];
            }
           
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }else{
        
    }
    
}

#pragma mark  拍照中获取

//保存图片到本地
-(void)SaveImageToLocal:(UIImage*)image keys:(NSString*)key{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:UIImagePNGRepresentation(image) forKey:key];
}
//本地是否有相关图片
-(BOOL)LocalHaveImage:(NSString*)key{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    NSData* imgData=[defaults objectForKey:key];
    if (imgData) {
        return YES;
    }
    return NO;
}


//从摄像头获取活动图片
-(void)pickImageFromCamera{
    UIImagePickerController* imagepicker=[[UIImagePickerController alloc] init];
    imagepicker.delegate=self;
    imagepicker.sourceType=UIImagePickerControllerSourceTypeCamera;
    imagepicker.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
    imagepicker.allowsEditing=YES;
    [self presentViewController:imagepicker animated:YES completion:^{
    }];
}


//保存图片到doucument
-(void)saveImage:(UIImage*)tempImage WithName:(NSString*)imageName{
    NSData* imageData=UIImagePNGRepresentation(tempImage);
    NSArray* paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory=[paths objectAtIndex:0];
    NSString* fullPathToFile=[documentsDirectory stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPathToFile atomically:NO];
}

-(NSString*)documentFolderPath{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}



#pragma mark UIImagePickerController delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage* image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
            
        }
        UIImage* image1=[MAToolUtils imageByScalingAndCroppingForSize:CGSizeMake(600, 800) andSourceImage:image];;
        [_imageArr addObject:image1];
        if (_imageArr.count>=5) {
            collectBgView.frame=CGRectMake(6, CGRectGetMaxY(_inputContent.frame)+10,kScreenWidth-12,160);
            _collectionView.frame=CGRectMake(6, 6,collectBgView.frame.size.width-12,collectBgView.frame.size.height-12);
            _locationView.frame=CGRectMake(6, CGRectGetMaxY(collectBgView.frame)+10, kScreenWidth-12,50);
            [_collectionView reloadData];
        }
        [_collectionView reloadData];
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        [textView resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    return YES;
}


-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length==0) {
        _placeholderLabel.text=@"请在此输入内容";
        
    }else{
        _placeholderLabel.text=@"";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
